import numpy as np
import matplotlib.pyplot as plt

data = np.array([
    [0.8, 1.0],
    [1.7, 0.9],
    [2.7, 2.5],
    [3.2, 2.9],
    [3.7, 2.8],
    [4.1, 3.5],
    [4.5, 3.7],
    [4.9, 4.6],
])

x_data = data[:, 0]
y_data = data[:, 1]

# 2. 前向传播 -- 拟合一条线，预测对应y的值
w = 0.9
b = 0
y_predict = w * x_data + b

# 3. 计算误差  ESM 均方误差
esm_loss = np.mean(np.square(y_data - y_predict))
print(esm_loss)

plt.subplot(121)
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.scatter(x_data, y_data, alpha=0.5, c='b')
plt.plot([0, 5], [w * 0 + b, w * 5 + b], c='r')

plt.subplot(122)
w_values = np.linspace(-2, 4, 1000)
loss_values = [np.mean((y_data - (w * x_data + b))**2) for w in w_values]
plt.plot(w_values, loss_values)
plt.show()
